﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.Crm.Sdk;
using Microsoft.Crm.Workflow;
using System.Workflow.ComponentModel.Compiler;
using System.Workflow.ComponentModel;
using Microsoft.Crm.Sdk.Query;
using Microsoft.Crm.SdkTypeProxy;

namespace CrmContrib.Workflow.Activities.Invoicing
{
    [CrmWorkflowActivity("Invoice Counter", "CrmContrib \\ Invoicing")]
    public class InvoiceCounterActivity : Activity
    {
        [CrmInput("SalesOrder")]
        [CrmReferenceTarget("salesorder")]
        [ValidationOption(ValidationOption.Required)]
        public Lookup SalesOrder
        {
            get { return (Lookup)base.GetValue(SalesOrderProperty); }
            set { base.SetValue(SalesOrderProperty, value); }
        }

        public static readonly DependencyProperty SalesOrderProperty = DependencyProperty.Register("SalesOrder", typeof(Lookup), typeof(InvoiceCounterActivity));

        [CrmInput("Boolean Attribute")]
        [ValidationOption(ValidationOption.Optional)]
        public string BooleanAttribute
        {
            get { return (string)base.GetValue(BooleanAttributeProperty); }
            set { base.SetValue(BooleanAttributeProperty, value); }
        }

        public static readonly DependencyProperty BooleanAttributeProperty = DependencyProperty.Register("BooleanAttribute", typeof(string), typeof(InvoiceCounterActivity));

        [CrmInput("Check For")]
        [ValidationOption(ValidationOption.Optional)]
        public CrmBoolean BooleanAttributeValue
        {
            get { return (CrmBoolean)base.GetValue(BooleanAttributeValueProperty); }
            set { base.SetValue(BooleanAttributeValueProperty, value); }
        }

        public static readonly DependencyProperty BooleanAttributeValueProperty = DependencyProperty.Register("BooleanAttributeValue", typeof(CrmBoolean), typeof(InvoiceCounterActivity));

        protected override ActivityExecutionStatus Execute(ActivityExecutionContext executionContext)
        {
            var contextService = executionContext.GetService<IContextService>();
            var workflowContext = contextService.Context;
            var crmService = workflowContext.CreateCrmService();

            //equivalent to: select RelatedEntityIDColumn from ParentEntityName where ParentEntityIDColumn = ParentEntityId 
            var query = new QueryExpression { EntityName = EntityName.invoice.ToString(), ColumnSet = new ColumnSet() };
            query.Criteria.AddCondition("salesorderid", ConditionOperator.Equal, SalesOrder.Value);
            if (!String.IsNullOrEmpty(BooleanAttribute))
            {
                query.Criteria.AddCondition(BooleanAttribute, ConditionOperator.Equal, BooleanAttributeValue.Value);
            }

            //should only be one record if select with primary key
            var response = (RetrieveMultipleResponse)crmService.Execute(new RetrieveMultipleRequest { ReturnDynamicEntities = true, Query = query });
            Count = new CrmNumber(response.BusinessEntityCollection.BusinessEntities.Count);

            return base.Execute(executionContext);
        }

        [CrmOutput("Count")]
        public CrmNumber Count
        {
            get { return (CrmNumber)base.GetValue(CountProperty); }
            set { base.SetValue(CountProperty, value); }
        }

        public static readonly DependencyProperty CountProperty = DependencyProperty.Register("Count", typeof(CrmNumber), typeof(InvoiceCounterActivity));
    }
}
